// script.js

function loadProducts() {
    fetch('http://localhost:3000/products') 
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            const productList = document.getElementById('product-list'); // get the product list element
            productList.innerHTML = ''; // clear the list

            data.forEach(product => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${product.name}</td>
                    <td>${product.unit_price}</td>
                    <td>${product.tax_rate}</td>
                    <td>${product.quantity}</td>
                `;
                productList.appendChild(row); // add row to the list
            });
        })
        .catch(error => {
            console.error('Error fetching products:', error);
        });
}

// The loadProducts function is called when the page loads
document.addEventListener('DOMContentLoaded', loadProducts);


document.getElementById('add-product-form').addEventListener('submit', function(event) {
    event.preventDefault();
  
    const name = document.getElementById('product-name').value;
    const unitPrice = document.getElementById('unit-price').value;
    const taxRate = 5.5; // tax rate is hardcoded for simplicity
    const quantity = document.getElementById('quantity').value;

    fetch('http://localhost:3000/products', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name, unit_price: unitPrice, tax_rate: taxRate, quantity }), // convert data to JSON format
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.text();
    })
    .then(data => {
        alert(data);
        loadProducts(); // reload the product list
    })
    .catch(error => console.error('Error:', error));
});

document.getElementById('update-stock-form').addEventListener('submit', function(event) {
    event.preventDefault();
  
    const productId = document.getElementById('stock-product-id').value; // get the product id
    const quantity = document.getElementById('stock-quantity').value; // get the new quantity

    fetch('http://localhost:3000/stock', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json', // set the content type to JSON
        },
        body: JSON.stringify({ product_id: productId, quantity }),
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok'); // check if the response is ok
        return response.text();
    })
    .then(data => {
        alert(data);
        loadProducts(); //
    })
    .catch(error => console.error('Error:', error)); // handle errors
});
